from django.shortcuts import get_object_or_404
from rest_framework.permissions import AllowAny, IsAuthenticatedOrReadOnly
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from home_design.models import Style
from home_design.serializers import StyleSerializer, StyleListSerializer


class MyStyleListView(APIView):
    """
    用户获取自己的风格单品作品
    """
    permission_classes = [IsAuthenticatedOrReadOnly]

    def get(self, request):
        styles = Style.objects.filter(designer=request.user)
        serializer = StyleSerializer(styles, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class StyleListView(APIView):
    """
     处理风格列表的视图，包括获取所有风格和创建新风格
    """
    permission_classes = [IsAuthenticatedOrReadOnly]

    def get(self, request):
        styles = Style.objects.all()
        serializer = StyleSerializer(styles, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def post(self, request):
        serializer = StyleSerializer(data=request.data, context={'request': request})
        if serializer.is_valid():
            serializer.save()  # 保存数据
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class StyleClassificationView(APIView):
    """
    处理风格分类的视图，包括获取所有风格分类
    """
    permission_classes = [IsAuthenticatedOrReadOnly]

    def get(self, request, classification):
        styles = Style.objects.filter(style_classification=classification)
        serializer = StyleSerializer(styles, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class StyleDetailView(APIView):
    """
    处理风格详情的视图，包括获取单个风格和更新风格
    """
    permission_classes = [IsAuthenticatedOrReadOnly]

    def get_object(self, pk):
        return get_object_or_404(Style, pk=pk)

    def get(self, request, pk):
        style = self.get_object(pk)
        serializer = StyleListSerializer(style, context={'request': request})
        return Response(serializer.data,status=status.HTTP_200_OK)

    def put(self, request, pk):
        style = self.get_object(pk)
        serializer = StyleSerializer(style, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk):
        style = self.get_object(pk)
        style.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
